from http import HTTPStatus

from errors import Missing
from flask import Blueprint, jsonify, request
from service import clients as service

bp = Blueprint("clients", __name__, url_prefix="/clients")


@bp.route("/", methods=["GET"])
def get_clients_list_route():
    """Получить список всех клиентов

    Example:
        curl http://127.0.0.1:8000/clients/ | jq
    """
    return jsonify(service.get_all_clients()), HTTPStatus.OK


@bp.route("/<int:client_id>", methods=["GET"])
def get_client_route(client_id: int):
    """Информация о клиенте по его ID

    Example:
        curl http://127.0.0.1:8000/clients/1 | jq
    """
    try:
        client = service.get_client(client_id)
    except Missing as ex:
        return jsonify({"error": ex.msg}), HTTPStatus.NOT_FOUND
    return jsonify(client), HTTPStatus.OK


@bp.route("/", methods=["POST"])
def create_client_route():
    """Создать нового клиента

    Examples:
        curl -X POST -H "Content-Type: application/json" \
        --data '{"name": "Petr", "surname": "Petrov", "credit_card": "1234567812345678", "car_number": "A000AA98"}' \
             http://127.0.0.1:8000/clients/
    """
    name = request.json.get("name", None)
    surname = request.json.get("surname", None)
    credit_card = request.json.get("credit_card", None)
    car_number = request.json.get("car_number", None)

    if name is None or surname is None or credit_card is None or car_number is None:
        return (
            jsonify({"error": "All client fields are required"}),
            HTTPStatus.BAD_REQUEST,
        )

    client = service.create_client(name, surname, credit_card, car_number)
    return jsonify(client), HTTPStatus.CREATED
